package com.canyou.system;

import com.canyou.api.BaseApiController;
import com.canyou.api.ResponseBO;
import com.canyou.constants.CommonConstants;
import com.canyou.constants.MsgConstants;
import com.canyou.system.entity.org.OrgDTO;
import com.canyou.system.entity.org.OrgDetailVO;
import com.canyou.system.entity.org.OrgListVO;
import com.canyou.system.model.Organization;
import com.canyou.system.service.OrganizationService;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

import static com.canyou.api.ResponseBO.*;

/**
 * 机构管理前端控制器
 *
 * @author canyou
 * @since 2019-06-03
 */
@Api(tags = "机构管理")
@ApiSort(1003)
@RestController
@RequestMapping("/org")
@Validated
public class OrganizationController extends BaseApiController {

    @Autowired
    private OrganizationService orgService;

    @ApiOperation(value = "获取机构树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgName", paramType = "query", value = "机构名称", dataType = "string"),
            @ApiImplicitParam(name = "contacts", paramType = "query", value = "机构联系人", dataType = "string")
    })
    @PreAuthorize("hasPerm('org')")
    @GetMapping("/get_org_tree")
    public ResponseBO<List<OrgListVO>> getOrgTree(@RequestParam(required = false) String orgName,
                                                  @RequestParam(required = false) String contacts) {
        List<OrgListVO> list = orgService.getOrgTree(orgName, contacts);
        return ok(list);
    }

    @ApiOperation(value = "获取机构详情")
    @ApiImplicitParam(name = "id", paramType = "query", value = "机构id", dataType = "int", required = true, example = "1")
    @PreAuthorize("hasPerm('org')")
    @GetMapping("/get_info")
    public ResponseBO<OrgDetailVO> getOrgDetail(@NotNull(message = "机构id不能为空")
                                                @RequestParam(required = false) Long id) {
        return ok(orgService.getDetailById(id));
    }

    @ApiOperation(value = "新增编辑机构")
    @PreAuthorize("hasPerm('org:add','org:edit')")
    @PostMapping("/save")
    public ResponseBO saveOrg(@ApiParam(name = "orgDTO", type = "OrgDTO", value = "机构新增编辑数据", required = true)
                              @Valid
                              @NotNull(message = "机构信息不能为空")
                              @RequestBody OrgDTO orgDTO) {
        Long orgId = orgDTO.getId();
        Long parentId = orgDTO.getParentId();
        // 父部机构不能为null
        if (!CommonConstants.DEFAULT_PARENT_ID.equals(parentId)) {
            Organization parentOrg = orgService.getById(parentId);
            if (parentOrg == null) {
                return illegal("parentId: " + parentId + "对应的父机构不存在");
            }
        }
        if (orgService.existOrg(orgDTO.getOrgName(), orgId)) {
            return illegal("机构名称已存在");
        }
        Organization org = new Organization();
        if (orgId != null) {
            org = orgService.getById(orgId);
            if (org == null) {
                return illegal("orgId: " + orgId + "对应的机构不存在");
            }
            if (orgId.equals(parentId)) {
                return illegal("父机构不能是本机构");
            }
        }
        BeanUtils.copyProperties(orgDTO, org);
        return result(orgService.saveOrUpdate(org), orgId);
    }

    @ApiOperation(value = "删除机构")
    @PreAuthorize("hasPerm('org:del')")
    @PostMapping("/remove")
    public ResponseBO removeOrg(@ApiParam(name = "id", type = "Long", value = "机构id", required = true, example = "1")
                                @Valid
                                @NotNull(message = "机构id不能为空")
                                @RequestBody Long id) {
        if (orgService.getChildCount(id) > 0) {
            return illegal("该机构存在子机构, 无法删除");
        }
        if (orgService.getOrgDeptCount(id) > 0) {
            return illegal("该机构下存在部门, 无法删除");
        }
        if (orgService.getOrgUserCount(id) > 0) {
            return illegal("该机构被用户使用, 无法删除");
        }
        return ok(orgService.removeById(id), MsgConstants.DEL_SUCCESS);
    }

}
